package cruds;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.CompoundPropertyModel;
import home.Home;
import panels.BodyPanel;
import services.GenericService;
import staticmenus.StaticMenu;

@SuppressWarnings("serial")
public abstract class CrudModifyParent<T> extends BodyPanel{

	private T item;
	
	private GenericService<T> service;
	
	public CrudModifyParent(Home home, T item) {
		super(home);
		this.item = item;
		this.initializeService();
		this.initialize();
	}

	private void initialize() {
		Form<T> form = new Form<T>("form", new CompoundPropertyModel<T>(this.item));
		form.setOutputMarkupId(true);
		this.add(form);
		this.createFormFields(form);
		this.createModifyButton(form);
		this.createCancelButton(form);
	}

	private void createCancelButton(Form<T> form) {
		form.add(new AjaxSubmitLink("cancel"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				CrudModifyParent.this.redirectIfCancel(target);
				CrudModifyParent.this.updateDynamicMenu(target);
			}

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				
			}
		});
	}


	private void createModifyButton(Form<T> form) {
		form.add(new AjaxSubmitLink("modify"){

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				CrudModifyParent.this.doUpdateAndRedirect(target);
				CrudModifyParent.this.updateDynamicMenu(target);
				StaticMenu menustatico = new StaticMenu(CrudModifyParent.this.getHome());
				menustatico.changePanel(target);
			}

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				
			}	
		});	
	}
	
	protected abstract void redirectIfCancel(AjaxRequestTarget target);

	protected abstract void doUpdateAndRedirect(AjaxRequestTarget target);

	protected abstract void updateDynamicMenu(AjaxRequestTarget target);

	protected abstract void createFormFields(Form<T> form);

	protected abstract void initializeService();

	public GenericService<T> getService() {
		return service;
	}

	public void setService(GenericService<T> service) {
		this.service = service;
	}

	public T getItem() {
		return item;
	}

	public void setItem(T item) {
		this.item = item;
	}

}
